package com.bp.hearthealth.pulse.lnapps.notification

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.bp.hearthealth.pulse.lnapps.BpApplication
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.bp_extension.UIHelperBp
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.NotificationTarget


object NotificationControlManager {

    private var pendingIntent: PendingIntent? = null

    /**
     * 是否打开通知
     */
    fun isOpenNotification(): Boolean {
        val notificationManager: NotificationManagerCompat = NotificationManagerCompat.from(
            ForegroundActivityManager.getCurrentActivity()!!
        )
        return notificationManager.areNotificationsEnabled()
    }

    /**
     * 跳转到系统设置页面去打开通知，注意在这之前应该有个Dialog提醒用户
     */
    fun openNotificationInSys() {
        val context = ForegroundActivityManager.getCurrentActivity()!!
        val intent = Intent()
        try {
            intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS

            //8.0及以后版本使用这两个extra.  >=API 26
            intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
            intent.putExtra(Settings.EXTRA_CHANNEL_ID, context.applicationInfo.uid)

            //5.0-7.1 使用这两个extra.  <= API 25, >=API 21
            intent.putExtra("app_package", context.packageName)
            intent.putExtra("app_uid", context.applicationInfo.uid)

            context.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()

            //其他低版本或者异常情况，走该节点。进入APP设置界面
            intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
            intent.putExtra("package", context.packageName)

            //val uri = Uri.fromParts("package", packageName, null)
            //intent.data = uri
            context.startActivity(intent)
        }
    }

    @SuppressLint("RemoteViewLayout", "DiscouragedApi", "LaunchActivityFromNotification")
    fun notifyCustomNotification(openPage: String, imageUrl: Uri, content: String) {
        val context = ForegroundActivityManager.getCurrentActivity() ?: return

        val name: String
        val CHANNEL_ID: String
        val description: String
        val action: String
        val requestCode: Int
        val intent = Intent(context, NotificationClickActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)

        if (openPage == "0") {
            // 心率
            name = UIHelperBp.getString(R.string._notification_heart_rate_str)
            CHANNEL_ID = "heart_rate_channel_id"
            description = "Heart Rate Notification"
            requestCode = 1
            action = Constants.NOTIFICATION_HEART_RATE_GUIDE
        } else {
            // 血压
            name = UIHelperBp.getString(R.string._notification_blood_pressure_str)
            CHANNEL_ID = "blood_pressure_channel_id"
            description = "Blood Pressure Notification"
            requestCode = 0
            action = Constants.NOTIFICATION_BLOOD_PRESSURE
        }

        // 如果应用程序进程被杀死，则通过点击通知启动应用程序
//        if (!BPActivityCollector.isAppProcessAlive()) {
//            val launchIntent = context.packageManager.getLaunchIntentForPackage(context.packageName)
//            context.startActivity(launchIntent)
//            return
//        }

        pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.getActivity(
                context, requestCode, intent.putExtra(
                    Constants.NOTIFICATION_ACTION, action
                ), PendingIntent.FLAG_IMMUTABLE
            )
        } else {
            PendingIntent.getActivity(
                context, requestCode, intent.putExtra(
                    Constants.NOTIFICATION_ACTION, action
                ), PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
            )
        }

        // 创建通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val mChannel =
                NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH)
            mChannel.description = description // 设置通知渠道描述
            val notificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(mChannel)
        }

        val notificationLayout = RemoteViews(context.packageName, R.layout.notification_small)
        val notificationLayoutExpanded =
            RemoteViews(context.packageName, R.layout.notification_large)

        notificationLayout.setTextViewText(R.id.notification_body, content)
        notificationLayoutExpanded.setTextViewText(R.id.notification_body, content)

        val notification =
            NotificationCompat.Builder(context, CHANNEL_ID)
                .setSmallIcon(R.mipmap.notification_test)
                .setStyle(NotificationCompat.DecoratedCustomViewStyle())
                .setColor(UIHelperBp.getColor(R.color.transparent))
                .setContentIntent(pendingIntent).setCustomContentView(notificationLayout)
//                .setOngoing(true) // 持续显示
//                .setAutoCancel(true) // 禁止通知被点击后自动取消
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .setAutoCancel(true)
                .setCustomBigContentView(notificationLayoutExpanded).build()

//        notification.fullScreenIntent = pendingIntent

        setImageUri(notificationLayout, imageUrl, notification)
        setImageUri(notificationLayoutExpanded, imageUrl, notification)

        val notificationManager =
            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(1, notification)
    }


    private fun setImageUri(
        notificationLayout: RemoteViews, imageUrl: Uri, notification: Notification
    ) {
        Glide.with(BpApplication.context).asBitmap().load(imageUrl).into(
            NotificationTarget(
                BpApplication.context,
                R.id.notification_image_url,
                notificationLayout,
                notification,
                1
            )
        )
    }
}
